package cn.org.mrliu.code.generator.dao;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import cn.org.mrliu.code.generator.bean.Column;
import cn.org.mrliu.code.generator.bean.Table;

public class DBOperation {
	public static String TABLE_SCHEMA = "ssm";

	public static Table getTable(final String tableName) {
		String sql = "select TABLE_COMMENT from information_schema. TABLES where TABLE_SCHEMA = ? and table_name = ?";
		Table table = DBUtil.query(sql, new ResultSetHandler<Table>() {
			@Override
			public Table handle(ResultSet rs) throws Exception {
				if (rs.next()) {
					return new Table(tableName, rs.getString("TABLE_COMMENT"));
				}
				return null;
			}
		}, TABLE_SCHEMA, tableName);
		System.out.println(table);
		return table;
	}

	public static List<Column> getColumns(String tableName) {
		StringBuffer sql = new StringBuffer();
		sql.append("select ");
		sql.append("ORDINAL_POSITION,");
		sql.append("COLUMN_NAME,");
		sql.append("COLUMN_COMMENT,");
		sql.append("DATA_TYPE,");
		sql.append("CHARACTER_MAXIMUM_LENGTH,");
		sql.append("COLUMN_DEFAULT,");
		sql.append("IS_NULLABLE,");
		sql.append("COLUMN_KEY ");
		sql.append("from information_schema.COLUMNS ");
		sql.append("where table_schema = ? ");
		sql.append("and ");
		sql.append("table_name = ?");
		System.out.println(sql);
		List<Column> columns = DBUtil.query(sql.toString(), new ResultSetHandler<List<Column>>() {
			@Override
			public List<Column> handle(ResultSet rs) throws Exception {
				List<Column> columns = new ArrayList<>();
				Column column = null;
				while (rs.next()) {
					column = new Column(rs.getInt("ORDINAL_POSITION"), rs.getString("COLUMN_NAME"),
							rs.getString("COLUMN_COMMENT"), rs.getString("DATA_TYPE"),
							rs.getInt("CHARACTER_MAXIMUM_LENGTH"), rs.getString("COLUMN_DEFAULT"),
							rs.getBoolean("IS_NULLABLE"), rs.getString("COLUMN_KEY"));
					columns.add(column);
					System.out.println(column);
				}
				return columns;
			}
		},TABLE_SCHEMA,tableName);
		return columns;
	}
}
